<template>
  <div class="profile-page">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <!-- 返回按钮 -->
      <div class="back-btn" @click="handleBack">
        <!-- 自定义箭头（模拟设计图） -->
        <div class="arrow"></div>
      </div>

      <!-- 导航菜单 -->
      <el-menu 
        class="sidebar-menu" 
        default-active="1"
        background-color="#fff"
        text-color="#333"
        active-text-color="#409eff"
        border-right="1px solid #e6e6e6"
        @select="handleMenuSelect"
      >
        <el-menu-item index="1">
          <i class="el-icon-user" style="margin-right: 8px;"></i>
          个人信息
        </el-menu-item>
        <el-menu-item index="2" @click="showWorks = true">
          <i class="el-icon-edit" style="margin-right: 8px;"></i>
          创作
        </el-menu-item>
      </el-menu>
    </aside>

    <!-- 右侧内容区 -->
    <section class="main-content" v-if="!showWorks">
      <!-- 个人信息卡片 -->
      <el-card class="profile-card">
        <!-- 头像容器 -->
        <div class="avatar-container">
          <img 
            :src="avatarUrl" 
            alt="用户头像" 
            class="avatar"
            @error="handleAvatarError"
            v-if="!isEditable"
          >
          <img 
            :src="avatarUrl" 
            alt="用户头像" 
            class="avatar avatar-editable"
            @error="handleAvatarError"
            v-if="isEditable"
            @click="triggerAvatarUpload"
            style="cursor:pointer"
          >
          <input 
            ref="avatarInput"
            type="file" 
            accept="image/*"
            style="display:none"
            @change="uploadAvatar"
          >
        </div>

        <!-- 信息表单 -->
        <el-form label-width="80px" class="profile-form">
          <el-form-item label="昵称">
            <el-input v-model="nickname" :disabled="!isEditable"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="email" disabled></el-input>
          </el-form-item>
          <el-form-item label="个人简介">
            <el-input
              type="textarea"
              v-model="bio"
              :disabled="!isEditable"
              :rows="3"
            ></el-input>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleEdit"
            >
              {{ isEditable ? '保存' : '编辑' }}
            </el-button>
            <el-button @click="handleLogout">退出登录</el-button>
            <el-button type="warning" @click="handleChangePassword">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 用户创作作品列表 -->
      <div class="user-posts">
        <div 
          class="post-card" 
          v-for="post in userPosts" 
          :key="post.id" 
          @click="handlePostClick(post)"
        >
          <img :src="post.cover" alt="作品封面" class="post-cover">
          <div class="post-info">
            <h3 class="post-title">{{ post.title }}</h3>
            <div class="post-meta">
              <span class="post-date">{{ post.date }}</span>
              <span class="post-likes">
                <i class="el-icon-like"></i> {{ post.likes }}
              </span>
              <span class="post-comments">
                <i class="el-icon-chat-line-round"></i> {{ post.comments }}
              </span>
            </div>
          </div>
        </div>

        <!-- 加载更多按钮 -->
        <div v-if="postTotal > userPosts.length" class="load-more">
          <el-button 
            :loading="isPostLoading" 
            @click="loadMorePosts"
            class="load-more-btn"
          >
            加载更多
          </el-button>
        </div>
      </div>
    </section>
    <!-- 创作作品展示区 -->
    <section class="main-content" v-else>
      <el-card class="profile-card">
        <h2 style="margin-bottom:20px;">我的创作</h2>
        <div class="card-grid">
          <div v-for="item in userPosts" :key="item.id" class="content-card" @click="handlePostClick(item)">
            <div class="cover" :style="{ backgroundImage: `url(${item.cover})` }"></div>
            <div class="card-content">
              <h3 class="title">{{ item.title }}</h3>
              <div class="stats">
                <span>👍 {{ item.likes }}</span>
                <span>💬 {{ item.comments }}</span>
                <span>{{ item.date }}</span>
              </div>
            </div>
          </div>
        </div>
        <div v-if="userPosts.length === 0 && !isPostLoading" class="empty">暂无作品</div>
        <div v-if="userPosts.length > 0 && userPosts.length < postTotal" class="load-more">
          <el-button @click="loadMorePosts" :loading="isPostLoading">加载更多</el-button>
        </div>
      </el-card>
    </section>
  </div>
</template>

<script>
// 导入API请求模块
import { user } from '@/utils/api'; // 修改为导入 user 模块
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';

export default {
  name: 'Profile',
  setup() {
    // 用户信息
    const nickname = ref('昵称');
    const email = ref('邮箱号');
    const bio = ref('简介');
    const isEditable = ref(false);
    const avatarUrl = ref('/default-avatar.png'); // 添加头像URL
    const avatarInput = ref(null);
    const showWorks = ref(false);

    // 头像错误处理
    const handleAvatarError = () => {
      avatarUrl.value = '/default-avatar.png';
    };

    // 上传头像（支持 base64 或文件）
    const uploadAvatar = async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      try {
        // 读取为 base64
        const reader = new FileReader();
        reader.onload = async (e) => {
          const base64 = e.target.result;
          // 直接用 base64 方式上传
          const response = await user.updateProfile({ avatar: base64 });
          if (response.status === 'success') {
            ElMessage.success('头像更新成功');
            avatarUrl.value = base64;
            fetchUserInfo();
          } else {
            ElMessage.error('头像更新失败');
          }
        };
        reader.readAsDataURL(file);
      } catch (error) {
        console.error('上传头像失败:', error);
        ElMessage.error('上传头像失败');
      }
    };

    // 头像点击触发上传
    const triggerAvatarUpload = () => {
      if (isEditable.value && avatarInput.value) {
        avatarInput.value.value = '';
        avatarInput.value.click();
      }
    };

    // 用户创作作品相关
    const userPosts = ref([]);
    const postPage = ref(1);
    const postPageSize = 30;
    const postTotal = ref(0);
    const isPostLoading = ref(false);

    // 加载当前用户的所有作品
    const fetchUserPosts = async (reset = false) => {
      if (isPostLoading.value) return;
      isPostLoading.value = true;
      try {
        const res = await user.getMyPosts({ page: postPage.value, pageSize: postPageSize });
        if (reset) userPosts.value = [];
        const newPosts = (res.posts || res.data || []).map(item => ({
          id: item._id || item.id,
          title: item.title,
          cover: item.cover,
          likes: item.likes,
          comments: Array.isArray(item.comments) ? item.comments.length : (item.comments || 0),
          date: item.createdAt ? new Date(item.createdAt).toISOString().slice(0, 10) : '',
        }));
        // 合并去重
        const ids = new Set(userPosts.value.map(i => i.id));
        userPosts.value = reset ? newPosts : [...userPosts.value, ...newPosts.filter(i => !ids.has(i.id))];
        postTotal.value = res.total || userPosts.value.length;
      } catch (e) {
        // 错误处理
      } finally {
        isPostLoading.value = false;
      }
    };
    // 用户信息加载
    const fetchUserInfo = async () => {
      try {
        const res = await user.getMe();
        if (res && res.data && res.data.user) {
          nickname.value = res.data.user.nickname || '昵称';
          email.value = res.data.user.email || '邮箱号';
          bio.value = res.data.user.bio || '';
          avatarUrl.value = res.data.user.avatar || '/default-avatar.png';
        }
      } catch (e) {
        // 错误处理
      }
    };
    // 左侧菜单点击事件
    const handleMenuSelect = (index) => {
      if (index === '2') {
        showWorks.value = true;
      } else {
        showWorks.value = false;
      }
    };
    // 首次加载
    onMounted(() => {
      fetchUserInfo();
      fetchUserPosts(true);
    });
    // 加载更多
    const loadMorePosts = async () => {
      if (isPostLoading.value) return;
      postPage.value++;
      await fetchUserPosts();
    };
    // 点击作品卡片
    const handlePostClick = (item) => {
      window.location.href = `/detail/${item.id}`;
    };

    // 返回逻辑
    const handleBack = () => {
      window.history.back()
    }

    // 编辑/保存逻辑
    const handleEdit = () => {
      if (isEditable.value) {
        // 保存修改
        saveUserInfo();
      }
      isEditable.value = !isEditable.value;
    };

    // 保存用户信息（昵称、简介）
    const saveUserInfo = async () => {
      try {
        const response = await user.updateProfile({ nickname: nickname.value, bio: bio.value });
        if (response && response.status === 'success') {
          ElMessage.success('信息保存成功');
          fetchUserInfo();
        } else {
          ElMessage.error('信息保存失败');
        }
      } catch (error) {
        console.error('信息保存失败:', error);
        ElMessage.error('信息保存失败');
      }
    };

    // 退出登录
    const handleLogout = () => {
      ElMessageBox.confirm(
        '确定退出登录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await user.logout();
        } catch (e) {}
        localStorage.removeItem('token');
        window.location.href = '/login';
      }).catch(() => {});
    };

    // 修改密码跳转到重置密码页面
    const handleChangePassword = () => {
      window.location.href = '/reset_password';
    };

    return {
      nickname,
      email,
      bio,
      isEditable,
      avatarUrl,
      avatarInput,
      userPosts,
      postTotal,
      isPostLoading,
      showWorks,
      handleBack,
      handleEdit,
      handleLogout,
      handleChangePassword,
      triggerAvatarUpload,
      uploadAvatar,
      loadMorePosts,
      handlePostClick,
      handleMenuSelect
    }
  }
}
</script>

<style scoped>
.profile-page {
  display: flex;
  height: 100vh;
  background-color: #f5f7fa;
}

/* 左侧导航栏 */
.sidebar {
  width: 220px;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
  box-shadow: 0 0 8px rgba(0,0,0,0.05);
}

/* 返回按钮 */
.back-btn {
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.3s;
  border-bottom: 1px solid #e6e6e6;
}
.back-btn:hover {
  background-color: #f8f9fa;
}

/* 自定义箭头（还原设计图） */
.arrow {
  width: 20px;
  height: 20px;
  border-left: 2px solid #333;
  border-bottom: 2px solid #333;
  transform: rotate(45deg);
}

/* 导航菜单 */
.sidebar-menu {
  flex: 1;
  border-right: none;
}
.el-menu-item {
  font-size: 14px;
  padding: 14px 20px;
}

/* 右侧内容区 */
.main-content {
  flex: 1;
  padding: 40px 80px;
  display: flex;
  flex-direction: column;
  align-items: center; /* 新增：内容水平居中 */
  justify-content: center;
}

/* 个人信息卡片 */
.profile-card {
  width: 600px; /* 加宽卡片 */
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin: 0 auto; /* 新增：卡片居中 */
}

/* 头像容器 */
.avatar-container {
  display: flex;
  justify-content: center;
  padding: 30px 0;
}
.avatar {
  width: 140px;
  height: 140px;
  background-color: #c0c0c0;
  border-radius: 50%;
}

/* 表单样式 */
.profile-form {
  padding: 20px 40px 40px;
}
.el-form-item {
  margin-bottom: 24px;
}
.el-input, .el-textarea {
  border-radius: 4px;
}

/* 按钮组 */
.el-form-item__content {
  display: flex;
  gap: 16px;
}

/* 用户创作作品列表 */
.user-posts {
  margin-top: 40px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.post-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: transform 0.3s;
}
.post-card:hover {
  transform: translateY(-2px);
}
.post-cover {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}
.post-info {
  padding: 16px;
}
.post-title {
  font-size: 18px;
  font-weight: 500;
  margin: 0 0 8px;
}
.post-meta {
  font-size: 14px;
  color: #999;
  display: flex;
  gap: 16px;
}

/* 加载更多按钮 */
.load-more {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.load-more-btn {
  width: 100%;
  max-width: 300px;
}

/* 创作作品展示区 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}
.content-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: transform 0.3s;
}
.content-card:hover {
  transform: translateY(-2px);
}
.cover {
  width: 100%;
  height: 120px;
  background-size: cover;
  background-position: center;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}
.card-content {
  padding: 16px;
}
.title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px;
}
.stats {
  font-size: 14px;
  color: #999;
  display: flex;
  gap: 16px;
}

/* 空状态 */
.empty {
  text-align: center;
  color: #999;
  padding: 40px 0;
}
</style>